package webhandler

import (
	"encoding/json"
	"gitee.com/geedchin/sweb/utils/crash"
	"gitee.com/geedchin/sweb/utils/strutil"
	"io/ioutil"
	"net/http"
)

type WebContext struct {
	reqBody []byte

	request  *http.Request
	response http.ResponseWriter
}

func (wh *WebContext) Ok(obj interface{}) {
	defer crash.Handler(nil)

	if tmp, ok := strutil.BytesOrString(obj); ok {
		wh.response.Write([]byte(tmp))
		return
	}
	result, err := json.Marshal(obj)
	if err != nil {
		wh.response.WriteHeader(http.StatusBadGateway)
		return
	}
	wh.response.Write(result)
}

func (wh *WebContext) Result(statusCode int, obj interface{}) {
	defer crash.Handler(nil)
	result, err := json.Marshal(obj)
	if err != nil {
		wh.response.WriteHeader(http.StatusBadGateway)
		return
	}
	wh.response.WriteHeader(statusCode)
	wh.response.Write(result)
}

func (wh *WebContext) BindBody(out interface{}) error {

	body, err := wh.Body()
	if err != nil {
		return err
	}
	return json.Unmarshal(body, out)
}

func (wh *WebContext) Body() ([]byte, error) {
	if len(wh.reqBody) > 0 {
		return wh.reqBody, nil
	}
	body, err := ioutil.ReadAll(wh.request.Body)
	if err != nil {
		return nil, err
	}
	wh.reqBody = body
	return body, err
}

func (wh *WebContext) BodyIgnoreErr() []byte {
	body, _ := wh.Body()
	return body
}

func (wh *WebContext) RequestHeader() http.Header {
	return wh.request.Header
}
